package com.longcai.piaojia.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longcai.piaojia.BaseApplication;
import com.longcai.piaojia.R;
import com.longcai.piaojia.conn.Conn;
import com.longcai.piaojia.dialog.WarnningDialog;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.scale.ScaleScreenHelperFactory;
import com.zcx.helper.util.UtilApp;
import com.zcx.helper.util.UtilMD5;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by Administrator on 2017/5/22.
 */

public class ChainActivity extends BaseActivity implements View.OnClickListener {


    WebView web_wv;
    @SuppressLint("JavascriptInterface")
    RelativeLayout title_right_ll;

    TextView title_right_name;
    private PopupWindow popupWindow;
    private RelativeLayout linearlayout_share;
    private String url;
    private String phone, token;
    @BoundView(R.id.title_share_ll)
    private LinearLayout title_share_ll;

    @BoundView(R.id.project_detail_web_bottom_ll)
    private LinearLayout project_detail_web_bottom_ll;

    @BoundView(R.id.title_latest_right_ll)
    private RelativeLayout title_latest_right_ll;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chain);
        web_wv = (WebView) findViewById(R.id.web_wv);
        // 支持js
        web_wv.getSettings().setJavaScriptEnabled(true);
        web_wv.setWebChromeClient(new WebChromeClient());
        web_wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

      /*  // 缩放
        web_wv.getSettings().setSupportZoom(true);
        web_wv.getSettings().setBuiltInZoomControls(false);

        web_wv.addJavascriptInterface(this, "android");*/


        title_right_ll = (RelativeLayout) findViewById(R.id.title_right_ll);
        title_right_name = (TextView) findViewById(R.id.title_right_name);
        linearlayout_share = (RelativeLayout) findViewById(R.id.linearlayout_share);
        // title_right_name.setText("分享");
        title_right_name.setTextColor(getResources().getColor(R.color.white));
        // title_right_ll.setVisibility(View.VISIBLE);
        title_right_name.setVisibility(View.VISIBLE);
        phone = BaseApplication.BasePreferences.readUserAccount();
        project_detail_web_bottom_ll.setOnClickListener(this);
        token = UtilMD5.MD5Encode(UtilMD5.MD5Encode(phone, "UTF-8") + UtilMD5.MD5Encode(Long.parseLong(phone) % 7 + "", "UTF-8"), "UTF-8");
        url = Conn.BASE_URL + Conn.WEB_REG_INDEX + "?phone=" + phone + "&token=" + token;
        title_share_ll.setOnClickListener(this);
        title_share_ll.setVisibility(View.VISIBLE);
        title_latest_right_ll.setVisibility(View.VISIBLE);
        title_latest_right_ll.setOnClickListener(this);
        title_latest_right_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (popupWindow == null) {
                    popupWindow = new PopupWindow(ChainActivity.this);
                    popupWindow.setContentView(initView());
                    // PopupWindow必须设置高度和宽度
                    popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(ChainActivity.this, R.drawable.popwindow_bg));
                    popupWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT); // 设置宽度
                    popupWindow.setHeight(LinearLayout.LayoutParams.MATCH_PARENT); // 设置popWin 高度
                    popupWindow.showAtLocation(linearlayout_share, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
                    popupWindow.setOutsideTouchable(true);// 设置后点击其他位置PopupWindow将消失
                } else if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    popupWindow.showAtLocation(linearlayout_share, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
                }

            }
        });


     /*   web_wv.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {

                web_wv.loadUrl("javascript:getvalue()");

                super.onPageFinished(view, url);
            }

        });*/

        String url = getIntent().getStringExtra("url");
        setTitleName(getIntent().getStringExtra("title"));
        setBackTrue();


        if (!TextUtils.isEmpty(url)) {

            web_wv.loadUrl(url);
            web_wv.setWebViewClient(new WebViewClient() {
                                        @Override
                                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                                            //  return super.shouldOverrideUrlLoading(view, url);


                                            if (url.startsWith("tel:")) {
                                                Intent intent = new Intent(Intent.ACTION_CALL,
                                                        Uri.parse(url));
                                                startActivity(intent);
                                            }  else if (url.startsWith("http:") || url.startsWith("https:")) {
                                                view.loadUrl(url);
                                            }


                                            //   return super.shouldOverrideUrlLoading(view, url);
                                            return true;
                                        }


                                    }
            );

        } else {

            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.project_detail_web_bottom_ll:
                new WarnningDialog(this, BaseApplication.BasePreferences.readCustomServiceTel(), getString(R.string.cancel_text), getString(R.string.confirm_text)) {
                    @Override
                    protected void onConfirm() {

                        UtilApp.call(ChainActivity.this, BaseApplication.BasePreferences.readCustomServiceTel());

                    }
                }.show();

                break;
        }
    }


    private View initView() {

        View view = View.inflate(this, R.layout.popwindow_my_setting_share, null);
        ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) view);
        RelativeLayout popwindow_main_rl = (RelativeLayout) view.findViewById(R.id.popwindow_main_rl);
        RelativeLayout my_setting_share_friend_rl = (RelativeLayout) view.findViewById(R.id.my_setting_share_friend_rl);
        RelativeLayout my_setting_share_pengyouquan_rl = (RelativeLayout) view.findViewById(R.id.my_setting_share_pengyouquan_rl);

        my_setting_share_friend_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                popupWindow.dismiss();
                showShare(ChainActivity.this, 1);

            }
        });

        my_setting_share_pengyouquan_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                popupWindow.dismiss();
                showShare(ChainActivity.this, 2);

            }
        });

        popwindow_main_rl.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                popupWindow.dismiss();

                return false;
            }
        });
        return view;

    }


    public void showShare(final Context context, int type) {

        Resources res = context.getResources();
        Bitmap bmp = BitmapFactory.decodeResource(res, R.mipmap.share_icon);

        if (type == 1) {

            Wechat.ShareParams shareParams = new Wechat.ShareParams();
            shareParams.shareType = Platform.SHARE_WEBPAGE;

//            shareParams.setText("邀请有礼！不花一分钱，不出一点力，朋友助力，即得实惠。注册即送5元儿童剧专享券，上不封顶！");
//            shareParams.setText(share_time + "\n" + share_address);
            shareParams.setText("邀请朋友一起免费约票");
            shareParams.setTitle("【呼朋唤友，邀请有礼！】");

            shareParams.setImageData(bmp);

//            http://api.heiyoupiao.com/index.php/web/reg/index

            shareParams.setUrl(url);

            Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
            wechat.setPlatformActionListener(new PlatformActionListener() {
                @Override
                public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

//                    UtilToast.show(context, context.getString(R.string.goods_info_share_success_text));

                }

                @Override
                public void onError(Platform platform, int i, Throwable throwable) {

//                    UtilToast.show(context, context.getString(R.string.goods_info_share_failed_text));

                }

                @Override
                public void onCancel(Platform platform, int i) {

//                    UtilToast.show(context, context.getString(R.string.goods_info_share_failed_text));

                }
            });

            wechat.share(shareParams);

        } else {

            WechatMoments.ShareParams shareParams = new WechatMoments.ShareParams();
            shareParams.shareType = Platform.SHARE_WEBPAGE;
            shareParams.setText("邀请有礼！不花一分钱，不出一点力，朋友助力，即得实惠。注册即送5元儿童剧专享券，上不封顶！");
//            shareParams.setText(share_time + "\n" + share_address);

            shareParams.setTitle("【呼朋唤友，邀请有礼！】");

            shareParams.setImageData(bmp);

            shareParams.setUrl(url);

            Platform wechatmoents = ShareSDK.getPlatform(WechatMoments.NAME);
            wechatmoents.setPlatformActionListener(new PlatformActionListener() {
                @Override
                public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

//                    UtilToast.show(context, context.getString(R.string.goods_info_share_success_text));

                }

                @Override
                public void onError(Platform platform, int i, Throwable throwable) {

//                    UtilToast.show(context, context.getString(R.string.goods_info_share_failed_text));

                }

                @Override
                public void onCancel(Platform platform, int i) {

//                    UtilToast.show(context, context.getString(R.string.goods_info_share_failed_text));

                }
            });

            wechatmoents.share(shareParams);

        }

    }

}
